package inutan.common.utils;

public class ZigZag {

    public static long encodeLong(long l) {
        return (l << 1) ^ (l >> 63);
    }

    public static long decodeLong(long l) {
        return (l >>> 1) ^ ((l << 63) >> 63);
    }

    public static int encodeInt(int i) {
        return (i << 1) ^ (i >> 31);
    }

    public static int decodeInt(int i) {
        return (i >>> 1) ^ ((i << 31) >> 31);
    }

    public static byte[] write(int n) {
        byte[] data = new byte[bytesRequired(n)];
        int idx = 0;
        while (true) {
            if((n & ~0x7F) == 0) {
                data[idx++] = (byte) n;
                break;
            } else {
                data[idx ++] = (byte) ((n & 0x7F) | 0X80);
                n >>>= 7;
            }
        }
        return data;
    }

    public static int bytesRequired(int i) {
        if(i < 0) throw new RuntimeException();
        if((i >>> 7) == 0) return 1;
        if((i >>> 14) == 0) return 2;
        if((i >>> 21) == 0) return 3;
        if((i >>> 28) == 0) return 4;
        return 5;
    }
}
